package tech.deepmind.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.stereotype.Component;

import tech.deepmind.util.ConfigManager;


@Component
public class BaseDao {
	private static String className = null;
	private static String url = null;
	private static String user = null;
	private static String password = null;
	private static Connection conn = null;
	private static PreparedStatement pstmt = null;
	static {
		try {
			ConfigManager config = ConfigManager.getInstance();
			className = config.getValue("driverClass");
			url = config.getValue("url");
			user = config.getValue("user");
			password = config.getValue("password");
			Class.forName(className);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getConnection() {
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void dopstmt(String sql, Object... params) {
		getConnection();
		if (!"".equals(sql) && sql != null) {
			if (params == null) {
				params = new Object[0];
			}
			try {
				pstmt = conn.prepareStatement(sql);
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i + 1, params[i]);
				}
				pstmt.execute();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public int getUpdateCount() throws SQLException {
		return this.pstmt.getUpdateCount();
	}

	public ResultSet getResultSet() throws SQLException {
		return this.pstmt.getResultSet();
	}
	public void closeAll(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null || !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
